<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>绑定管理与修改密码</title>
    <link href="/api/assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="/api/assets/css/bootstrap-icons.css" rel="stylesheet">
    <style>
        .container { 
            margin-top: 20px; 
            max-width: 800px; 
        }
        .binding-card {
            margin-bottom: 15px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .binding-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        .user-list {
            max-height: 400px;
            overflow-y: auto;
        }
        .user-item {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            padding: 12px;
            border-bottom: 1px solid #dee2e6;
            gap: 10px;
        }
        .user-item:last-child {
            border-bottom: none;
        }
        .user-info {
            flex-grow: 1;
            font-size: 0.9rem;
        }
        .user-info > div {
            margin-bottom: 4px;
        }
        .cost-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 8px;
            margin-top: 6px;
        }
        .cost-item {
            background-color: #f8f9fa;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.85em;
            white-space: nowrap;
        }
        .cost-item span {
            font-weight: 500;
            color: #0d6efd;
        }
        .user-actions {
            display: flex;
            gap: 8px;
        }
        .user-actions .btn {
            padding: 4px 8px;
            font-size: 0.85rem;
        }
        .add-binding-form {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .logout-btn {
            position: fixed;
            top: 20px;
            right: 20px;
        }
        .float-button {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            background-color: #0d6efd;
            color: white;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            text-align: center;
            line-height: 50px;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            transition: all 0.3s ease;
        }
        .float-button:hover {
            transform: scale(1.1);
            box-shadow: 0 3px 8px rgba(0,0,0,0.3);
        }
        .float-button.back {
            background-color: #6c757d;
        }
        .nav-tabs .nav-link {
            color: #495057;
            border: none;
            border-bottom: 2px solid transparent;
            padding: 10px 20px;
        }
        .nav-tabs .nav-link.active {
            color: #0d6efd;
            background: none;
            border: none;
            border-bottom: 2px solid #0d6efd;
        }
        .tab-content {
            padding-top: 20px;
        }
        .cost-table th, .cost-table td {
            padding: 8px;
            font-size: 0.9rem;
        }
        .cost-summary-card {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .cost-summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 10px;
            margin-bottom: 15px;
        }
        .cost-stat-item {
            background: white;
            padding: 10px;
            border-radius: 6px;
            text-align: center;
        }
        .cost-stat-value {
            font-size: 1.2rem;
            font-weight: 500;
            color: #0d6efd;
        }
        .cost-stat-label {
            font-size: 0.85rem;
            color: #6c757d;
        }
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .refresh-btn {
            padding: 4px 8px;
            font-size: 0.9rem;
        }
        .refresh-btn i {
            margin-right: 4px;
        }
        .toggle-info-btn {
            padding: 4px 8px;
            font-size: 0.9rem;
            margin-left: 8px;
        }
        .sensitive-info {
            transition: filter 0.3s ease;
        }
        .sensitive-info.hidden {
            filter: blur(4px);
        }
        .sensitive-info.hidden:hover {
            filter: blur(0);
        }
        @media (max-width: 480px) {
            .container {
                margin-top: 15px;
                padding-left: 10px;
                padding-right: 10px;
            }
            .user-item {
                padding: 8px;
            }
            .cost-stats {
                grid-template-columns: repeat(2, 1fr);
            }
            .cost-item {
                padding: 3px 6px;
                font-size: 0.8em;
            }
            .cost-stat-item {
                padding: 8px;
            }
            .cost-stat-value {
                font-size: 1rem;
            }
        }
        /* 添加时钟悬浮窗样式 */
        .floating-clock {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 1001;
            background-color: rgba(13, 110, 253, 0.9);
            color: white;
            border-radius: 8px;
            padding: 10px 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            cursor: move;
            user-select: none;
            font-size: 1.1rem;
            min-width: 120px;
            text-align: center;
        }
        .drag-indicator {
            font-size: 0.5rem;
            margin-top: 5px;
            opacity: 0.7;
        }
    </style>
</head>
<body>
    <!-- 返回按钮悬浮球 -->
    <div class="float-button back" onclick="location.href='/api/event-search.html'" title="返回查询">
        <i class="bi bi-arrow-left"></i>
    </div>

    <!-- 悬浮时钟窗口 -->
    <div id="floatingClock" class="floating-clock">
        <div id="currentTime">00:00:00</div>
        <div class="drag-indicator">可拖动 结账需要</div>
    </div>

    <div class="container">
        <button class="btn btn-outline-danger logout-btn" onclick="handleLogout()">
            <i class="bi bi-box-arrow-right"></i> 退出登录
        </button>

        <!-- 标签页导航 -->
        <ul class="nav nav-tabs mb-3" id="myTab" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="accounts-tab" data-bs-toggle="tab" data-bs-target="#accounts" type="button" role="tab">
                    账号管理
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="costs-tab" data-bs-toggle="tab" data-bs-target="#costs" type="button" role="tab">
                    数据统计
                </button>
            </li>
        </ul>

        <!-- 标签页内容 -->
        <div class="tab-content" id="myTabContent">
            <!-- 账号管理标签页 -->
            <div class="tab-pane fade show active" id="accounts" role="tabpanel">
                <div class="add-binding-form">
                    <h5>快速添加绑定</h5>
                    <div class="row">
                        <div class="col-md-8">
                            <input type="text" class="form-control" id="quickNickId" placeholder="NickID">
                        </div>
                        <div class="col-md-4">
                            <button class="btn btn-primary w-100" onclick="quickAddBinding()">
                                <i class="bi bi-plus-circle"></i> 快速添加
                            </button>
                        </div>
                    </div>
                </div>

                <div class="card binding-card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">已绑定用户列表</h5>
                        <div>
                            <button class="btn btn-outline-primary btn-sm toggle-info-btn" onclick="toggleSensitiveInfo()">
                                <i class="bi bi-eye"></i> 显示/隐藏
                            </button>
                            <button class="btn btn-outline-secondary btn-sm refresh-btn" onclick="loadBindings()">
                                <i class="bi bi-arrow-clockwise"></i> 刷新
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="user-list" id="userList">
                            <!-- 用户列表将通过JavaScript动态加载 -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- 数据统计标签页 -->
            <div class="tab-pane fade" id="costs" role="tabpanel">
                <div class="cost-summary-card">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0">数据统计</h5>
                        <div>
                            <button class="btn btn-outline-primary btn-sm toggle-info-btn" onclick="toggleSensitiveInfo()">
                                <i class="bi bi-eye"></i> 显示/隐藏
                            </button>
                            <button class="btn btn-outline-secondary btn-sm refresh-btn" onclick="loadCostSummaries(1)">
                                <i class="bi bi-arrow-clockwise"></i> 刷新
                            </button>
                        </div>
                    </div>
                    <div class="cost-summary-grid">
                        <div class="cost-stat-item">
                            <div class="cost-stat-value" id="totalTodayCost">¥0.00</div>
                            <div class="cost-stat-label">今日总数据</div>
                        </div>
                        <div class="cost-stat-item">
                            <div class="cost-stat-value" id="totalYesterdayCost">¥0.00</div>
                            <div class="cost-stat-label">昨日总数据</div>
                        </div>
                        <div class="cost-stat-item">
                            <div class="cost-stat-value" id="totalWeekCost">¥0.00</div>
                            <div class="cost-stat-label">本周总数据</div>
                        </div>
                        <div class="cost-stat-item">
                            <div class="cost-stat-value" id="totalMonthCost">¥0.00</div>
                            <div class="cost-stat-label">本月总数据</div>
                        </div>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table table-striped table-hover cost-table">
                        <thead class="table-light">
                            <tr>
                                <th>昵称</th>
                                <th>NickID</th>
                                <th>数据</th>
                                <th>时间</th>
                            </tr>
                        </thead>
                        <tbody id="costTableBody">
                            <!-- 数据数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>

                <nav>
                    <ul class="pagination justify-content-center" id="costPagination">
                    </ul>
                </nav>
            </div>
        </div>

        <h2 class="mt-4">修改密码</h2>
        <form id="changePasswordForm">
            <div class="mb-3">
                <label for="oldPassword" class="form-label">旧密码</label>
                <input type="password" class="form-control" id="oldPassword" required>
            </div>
            <div class="mb-3">
                <label for="newPassword" class="form-label">新密码</label>
                <input type="password" class="form-control" id="newPassword" required>
            </div>
            <button type="submit" class="btn btn-primary">修改密码</button>
        </form>
    </div>

    <script src="/api/assets/js/bootstrap.bundle.min.js"></script>
    <script>
        // 页面加载时检查登录状态并加载数据
        document.addEventListener('DOMContentLoaded', function() {
            checkLoginStatus();
            loadBindings();
            loadCostSummaries(1);
            initFloatingClock(); // 初始化悬浮时钟
        });

        // 初始化悬浮时钟
        function initFloatingClock() {
            // 更新时间显示
            updateClock();
            setInterval(updateClock, 1000);
            
            // 使时钟窗口可拖动
            makeDraggable(document.getElementById('floatingClock'));
        }

        // 更新时钟显示
        function updateClock() {
            const now = new Date();
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            document.getElementById('currentTime').textContent = `${hours}:${minutes}:${seconds}`;
        }

        // 让元素可拖动
        function makeDraggable(element) {
            let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
            
            element.onmousedown = dragMouseDown;
            
            function dragMouseDown(e) {
                e = e || window.event;
                e.preventDefault();
                // 获取鼠标点击的初始位置
                pos3 = e.clientX;
                pos4 = e.clientY;
                document.onmouseup = closeDragElement;
                // 鼠标移动事件
                document.onmousemove = elementDrag;
            }
            
            function elementDrag(e) {
                e = e || window.event;
                e.preventDefault();
                // 计算新位置
                pos1 = pos3 - e.clientX;
                pos2 = pos4 - e.clientY;
                pos3 = e.clientX;
                pos4 = e.clientY;
                // 设置元素的新位置
                element.style.top = (element.offsetTop - pos2) + "px";
                element.style.left = (element.offsetLeft - pos1) + "px";
            }
            
            function closeDragElement() {
                // 停止移动
                document.onmouseup = null;
                document.onmousemove = null;
            }
            
            // 添加触摸事件支持
            element.ontouchstart = function(e) {
                pos3 = e.touches[0].clientX;
                pos4 = e.touches[0].clientY;
                document.ontouchend = closeTouchDragElement;
                document.ontouchmove = touchElementDrag;
            };
            
            function touchElementDrag(e) {
                e.preventDefault();
                pos1 = pos3 - e.touches[0].clientX;
                pos2 = pos4 - e.touches[0].clientY;
                pos3 = e.touches[0].clientX;
                pos4 = e.touches[0].clientY;
                element.style.top = (element.offsetTop - pos2) + "px";
                element.style.left = (element.offsetLeft - pos1) + "px";
            }
            
            function closeTouchDragElement() {
                document.ontouchend = null;
                document.ontouchmove = null;
            }
        }

        function checkLoginStatus() {
            fetch('/api/auth/check')
                .then(response => response.json())
                .then(data => {
                    if (data.code !== 200) {
                        window.location.href = '/api/login-register.html';
                    }
                })
                .catch(() => {
                    window.location.href = '/api/login-register.html';
                });
        }

        function loadBindings() {
            fetch('/api/binding/list')
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        displayBindings(data.data);
                    } else {
                        alert(data.message);
                    }
                })
                .catch(() => {
                    alert('加载绑定列表失败，请稍后重试');
                });
        }

        // 添加敏感信息显示/隐藏状态
        let isSensitiveInfoVisible = true;

        // 切换敏感信息显示/隐藏
        function toggleSensitiveInfo() {
            isSensitiveInfoVisible = !isSensitiveInfoVisible;
            document.querySelectorAll('.sensitive-info').forEach(el => {
                if (isSensitiveInfoVisible) {
                    el.classList.remove('hidden');
                } else {
                    el.classList.add('hidden');
                }
            });
        }

        // 修改显示绑定列表的函数
        function displayBindings(bindings) {
            const userList = document.getElementById('userList');
            userList.innerHTML = '';

            if (!bindings || bindings.length === 0) {
                userList.innerHTML = '<div class="text-center text-muted">暂无绑定用户</div>';
                return;
            }

            bindings.forEach(binding => {
                const userItem = document.createElement('div');
                userItem.className = 'user-item';
                userItem.innerHTML = `
                    <div class="user-info">
                        <div>
                            <strong>昵称：</strong><span class="sensitive-info ${!isSensitiveInfoVisible ? 'hidden' : ''}">${binding.nickname || '-'}</span>
                            <small class="text-muted ms-2">NickID: <span class="sensitive-info ${!isSensitiveInfoVisible ? 'hidden' : ''}">${binding.nickId || '-'}</span></small>
                        </div>
                        <div class="cost-stats">
                            <div class="cost-item">
                                今日：<span>¥${(parseFloat(binding.todayCost || 0)).toFixed(2)}</span>
                            </div>
                            <div class="cost-item">
                                昨日：<span>¥${(parseFloat(binding.yesterdayCost || 0)).toFixed(2)}</span>
                            </div>
                            <div class="cost-item">
                                本周：<span>¥${(parseFloat(binding.weekCost || 0)).toFixed(2)}</span>
                            </div>
                            <div class="cost-item">
                                本月：<span>¥${(parseFloat(binding.monthCost || 0)).toFixed(2)}</span>
                            </div>
                        </div>
                    </div>
                    <div class="user-actions">
                        <button class="btn btn-danger btn-sm" onclick="removeBinding('${binding.nickId}')">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                `;
                userList.appendChild(userItem);
            });
        }

        function addBinding() {
            const nickname = document.getElementById('nickname').value.trim();
            const nickId = document.getElementById('nickId').value.trim();

            if (!nickname && !nickId) {
                alert('请至少输入昵称或NickID其中之一');
                return;
            }

            fetch('/api/binding/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    nickname: nickname,
                    nickId: nickId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    alert(data.message || '添加绑定成功');
                    $('#addBindingModal').modal('hide');
                    loadBindings();
                } else {
                    alert(data.message || '添加绑定失败');
                }
            })
            .catch(() => {
                alert('添加绑定失败，请稍后重试');
            });
        }

        function quickAddBinding() {
            const nickId = document.getElementById('quickNickId').value.trim();
            
            if (!nickId) {
                alert('请输入NickID');
                return;
            }
            
            fetch('/api/binding/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ nickId })
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message || '添加绑定成功');
                if (data.code === 200) {
                    document.getElementById('quickNickId').value = '';
                    loadBindings();
                }
            })
            .catch(() => {
                alert('添加绑定失败，请稍后重试');
            });
        }
        
        function removeBinding(nickId) {
            if (!confirm('确定要解除该用户的绑定吗？')) {
                return;
            }

            fetch('/api/binding/remove', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ nickId })
            })
            .then(response => response.json())
            .then(data => {
                alert('解除绑定成功');
                if (data.code === 200) {
                    loadBindings();
                }
            })
            .catch(() => {
                alert('解除绑定失败，请稍后重试');
            });
        }

        function handleLogout() {
            fetch('/api/auth/logout',{
                method: 'POST',
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        window.location.href = '/api/login-register.html';
                    }
                })
                .catch(() => {
                    window.location.href = '/api/login-register.html';
                });
        }

        // 修改密码逻辑
        document.getElementById('changePasswordForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const oldPassword = document.getElementById('oldPassword').value;
            const newPassword = document.getElementById('newPassword').value;

            fetch('/api/binding/changePassword', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ oldPassword, newPassword })
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if (data.code === 200) {
                    window.location.href = '/api/login-register.html';
                }
            })
            .catch(() => {
                alert('修改密码失败，请稍后重试');
            });
        });

        // 加载数据汇总数据
        function loadCostSummaries(page = 1) {
            fetch('/api/binding/bound-users-summary?page=' + page)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        displayCostSummaries(data.data);
                        updateCostPagination(data.data);
                        updateTotalStats(data.data.stats);
                    }
                })
                .catch(error => {
                    console.error('加载数据数据失败:', error);
                });
        }

        // 修改显示成本数据的函数
        function displayCostSummaries(data) {
            const tbody = document.getElementById('costTableBody');
            tbody.innerHTML = '';

            if (!data.records || data.records.length === 0) {
                tbody.innerHTML = '<tr><td colspan="4" class="text-center">暂无数据</td></tr>';
                return;
            }

            data.records.forEach(record => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td><span class="sensitive-info ${!isSensitiveInfoVisible ? 'hidden' : ''}">${record.nickname || '-'}</span></td>
                    <td><span class="sensitive-info ${!isSensitiveInfoVisible ? 'hidden' : ''}">${record.nickId || '-'}</span></td>
                    <td>¥${record.userCost?.toFixed(2) || '0.00'}</td>
                    <td>${record.createTime || '-'}</td>
                `;
                tbody.appendChild(row);
            });
        }

        // 更新数据分页
        function updateCostPagination(data) {
            const pagination = document.getElementById('costPagination');
            pagination.innerHTML = '';

            if (!data || !data.total) return;

            const totalPages = Math.ceil(data.total / data.size);
            const currentPage = data.current;

            // 上一页
            const prevLi = document.createElement('li');
            prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
            prevLi.innerHTML = `
                <a class="page-link" href="#" onclick="event.preventDefault(); ${currentPage > 1 ? `loadCostSummaries(${currentPage - 1})` : ''}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            `;
            pagination.appendChild(prevLi);

            // 显示有限的页码，最多显示5个页码
            const maxPagesToShow = 5;
            let startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2));
            let endPage = Math.min(totalPages, startPage + maxPagesToShow - 1);
            
            // 调整起始页，确保总是显示maxPagesToShow个页码（如果总页数足够）
            if (totalPages > maxPagesToShow && endPage - startPage + 1 < maxPagesToShow) {
                startPage = Math.max(1, endPage - maxPagesToShow + 1);
            }

            // 第一页（如果不在当前显示范围内）
            if (startPage > 1) {
                const li = document.createElement('li');
                li.className = 'page-item';
                li.innerHTML = `
                    <a class="page-link" href="#" onclick="event.preventDefault(); loadCostSummaries(1)">1</a>
                `;
                pagination.appendChild(li);
                
                // 添加省略号
                if (startPage > 2) {
                    const ellipsis = document.createElement('li');
                    ellipsis.className = 'page-item disabled';
                    ellipsis.innerHTML = '<span class="page-link">...</span>';
                    pagination.appendChild(ellipsis);
                }
            }

            // 显示页码
            for (let i = startPage; i <= endPage; i++) {
                const li = document.createElement('li');
                li.className = `page-item ${i === currentPage ? 'active' : ''}`;
                li.innerHTML = `
                    <a class="page-link" href="#" onclick="event.preventDefault(); loadCostSummaries(${i})">${i}</a>
                `;
                pagination.appendChild(li);
            }

            // 最后一页（如果不在当前显示范围内）
            if (endPage < totalPages) {
                // 添加省略号
                if (endPage < totalPages - 1) {
                    const ellipsis = document.createElement('li');
                    ellipsis.className = 'page-item disabled';
                    ellipsis.innerHTML = '<span class="page-link">...</span>';
                    pagination.appendChild(ellipsis);
                }
                
                const li = document.createElement('li');
                li.className = 'page-item';
                li.innerHTML = `
                    <a class="page-link" href="#" onclick="event.preventDefault(); loadCostSummaries(${totalPages})">${totalPages}</a>
                `;
                pagination.appendChild(li);
            }

            // 下一页
            const nextLi = document.createElement('li');
            nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
            nextLi.innerHTML = `
                <a class="page-link" href="#" onclick="event.preventDefault(); ${currentPage < totalPages ? `loadCostSummaries(${currentPage + 1})` : ''}" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            `;
            pagination.appendChild(nextLi);
        }

        // 更新总计统计数据
        function updateTotalStats(stats) {
            if (!stats) return;

            document.getElementById('totalTodayCost').textContent = `¥${(stats.today?.total_cost || 0).toFixed(2)}`;
            document.getElementById('totalYesterdayCost').textContent = `¥${(stats.yesterday?.total_cost || 0).toFixed(2)}`;
            document.getElementById('totalWeekCost').textContent = `¥${(stats.week?.total_cost || 0).toFixed(2)}`;
            document.getElementById('totalMonthCost').textContent = `¥${(stats.month?.total_cost || 0).toFixed(2)}`;
        }
    </script>
</body>
</html> 